package xworker.swt.dataObject.datastore;

import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.swt.app.view.swt.widgets.PagingToolbar;
import xworker.dataObject.DataObjectList;
import xworker.dataObject.DataStore;
import xworker.dataObject.DataStoreListener;
import xworker.dataObject.PageInfo;

import java.util.Map;

public class PagingToolbarDataStoreListener  extends ControlDataStoreListener implements DataStoreListener{
    PagingToolbar pagingToolbar;
    public PagingToolbarDataStoreListener(PagingToolbar pagingToolbar, DataStore dataStore, ActionContext actionContext){
        super(pagingToolbar.pagingComposite, dataStore, actionContext);

        this.pagingToolbar = pagingToolbar;
        this.pagingToolbar.setDataStore(dataStore);

        pagingToolbar.pagingComposite.addDisposeListener(event -> dataStore.removeListener(this));
        dataStore.addListener(this);
    }

    public PagingToolbar getPagingToolbar() {
        return pagingToolbar;
    }

    @Override
    public void onReconfig(DataStore dataStore, Thing dataObject) {
    }

    @Override
    public void onLoaded(DataStore dataStore) {

    }

    @Override
    public void onTotalCountUpdated(DataStore dataStore) {
        exec(() ->{
            long currentPage;
            long totalPage;
            long start = 0;
            long totalCount;
            long offset;
            long limit = 0;
            DataObjectList records = dataStore.getDatas();

            if(dataStore.getPageInfo() != null){
                PageInfo pageInfo =dataStore.getPageInfo();

                if(pageInfo.getTotalCount() == 0){
                    totalCount = records != null ? records.size() : 0;
                }else{
                    totalCount = (int) pageInfo.getTotalCount();
                }
                start = (int) pageInfo.getStart();
                limit = (int) pageInfo.getLimit();
                if(limit > 0){
                    totalPage = totalCount / limit + (totalCount % limit > 0 ? 1 : 0);
                    currentPage = start / limit + 1;
                }else{
                    totalPage = 1;
                    currentPage = 1;
                }
                offset = start + (records != null ? (records.size() -1) : 0);
            }else{
                totalCount = records != null ? records.size() : 0;
                totalPage = 1;
                currentPage = 1;
                offset = totalCount;
            }

            pagingToolbar.setValues(totalCount, totalPage, currentPage, start, limit, offset);
        });
    }

    @Override
    public void onChanged(DataStore dataStore) {

    }

    @Override
    public void beforeLoad(DataStore dataStore, Thing condition, Map<String, Object> params) {

    }

    @Override
    protected void selectionChanged() {

    }
}
